<template>
  <px-form-item ref="formItem" label="盘点周期" :rules="rules" prop="cyclePerNum,cyclePerUnit,cycleTime,cycleValue" class="check-cycle-form">
    <div class="block w-[100%]">
      <px-row>
        <span class="check-cycle-form-text">每</span>
        <px-col :span="2">
          <px-form-item prop="cyclePerNum">
            <px-input-number
              v-model="cyclePerNum"
              :min="1"
              :max="cyclePerUnit == 'DAY' ? 99 : 12"
              controls-position="right"
              @change="handlePerNumChange"
            />
          </px-form-item>
        </px-col>
        <px-col :span="2">
          <px-form-item prop="cyclePerUnit" class="pl-[10px] pr-[5px]">
            <px-select v-model="cyclePerUnit" @change="handlePerUnitChange">
              <px-option v-for="item in unitList" :key="item.value" :label="item.label" :value="item.value" />
            </px-select>
          </px-form-item>
        </px-col>
        <span v-if="cyclePerUnit !== 'DAY'" class="check-cycle-form-text">的</span>
        <px-col :span="8">
          <WeekSelect v-if="cyclePerUnit === 'WEEK'" v-model="weekSelected" @weekChange="weekChange" />
          <DaySelect v-if="cyclePerUnit === 'MONTH'" v-model="daySelected" @dayChange="dayChange" />
          <MonthSelect
            v-if="['QUARTER', 'HALF_YEAR', 'YEAR'].includes(cyclePerUnit)"
            v-model="monthSelected"
            :type="cyclePerUnit"
            @monthChange="monthChange"
          />
        </px-col>
        <!-- <span v-if="['QUARTER', 'HALF_YEAR', 'YEAR'].includes(cyclePerUnit)" class="check-cycle-form-text">月</span> -->
        <px-col v-if="['QUARTER', 'HALF_YEAR', 'YEAR'].includes(cyclePerUnit)" :span="8">
          <DaySelect v-model="daySelected" @dayChange="dayChange" />
        </px-col>
      </px-row>
    </div>
  </px-form-item>
</template>

<script setup lang="ts">
import { queryDictData } from "@/api/common";
import DaySelect from "@/views/erc/inspect/components/DaySelect.vue";
import MonthSelect from "@/views/erc/inspect/components/MonthSelect.vue";
import WeekSelect from "@/views/erc/inspect/components/WeekSelect.vue";
import { nextTick, onMounted, ref, watch } from "vue";

// 父级方法和值
const emits = defineEmits(["handlePerNumChange", "handlePerUnitChange"]);
const cyclePerNum = defineModel("cyclePerNum");
const cyclePerUnit = defineModel("cyclePerUnit"); //	排查周期单位 DAY-日,WEEK-周,MONTH-月,YEAR-年
const cycleValue = defineModel("cycleValue");
const weekSelected = ref([]);
const daySelected = ref([]);
const monthSelected = ref([]);
const unitList = [
  { label: "周", value: "WEEK" },
  { label: "月", value: "MONTH" },
  { label: "年", value: "YEAR" }
];

const checkGroupVal = ref("");
const checkGroupList = ref([]);
const formItem = ref();
const rules = ref({
  required: true,
  trigger: "change",
  validator: validatatePass
});
function validatatePass(rule: any, value: any, callback: any) {
  if (
    (cyclePerUnit.value !== "DAY" && !cycleValue.value) ||
    (["QUARTER", "HALF_YEAR", "YEAR"].includes(cyclePerUnit.value) && (daySelected.value.length === 0 || monthSelected.value.length === 0))
  ) {
    let alertName = "";
    if (["QUARTER", "HALF_YEAR", "YEAR"].includes(cyclePerUnit.value)) {
      alertName = "月、日";
    }
    if (cyclePerUnit.value === "WEEK") {
      alertName = "星期";
    }
    if (cyclePerUnit.value === "MONTH") {
      alertName = "日";
    }
    callback(new Error(`请选择周期的${alertName}`));
  } else {
    callback();
  }
}
// watch(cyclePerUnit, val => {
//   console.log("周期单位", val);
//   // cycleValue.value = "";
//   // daySelected.value = [];
//   // monthSelected.value = [];
//   // weekSelected.value = [];

//   nextTick(() => {
//     formItem?.value?.clearValidate();
//   });
// });
watch(
  cycleValue,
  val => {
    if (["QUARTER", "HALF_YEAR", "YEAR"].includes(cyclePerUnit.value)) {
      if (!cycleValue.value) {
        daySelected.value = [];
        monthSelected.value = [];
        return;
      }
      const [month, day] = (cycleValue.value as string).split("-");
      if (day) {
        daySelected.value = day.split(",");
      } else {
        daySelected.value = [];
      }
      if (month) {
        monthSelected.value = month.split(",");
      } else {
        monthSelected.value = [];
      }
    } else if (cyclePerUnit.value === "DAY") {
      if (!cycleValue.value) {
        daySelected.value = [];
        return;
      }
      daySelected.value = (cycleValue.value as string).split(",");
    } else if (cyclePerUnit.value === "WEEK") {
      if (!cycleValue.value) {
        weekSelected.value = [];
        return;
      }
      console.log("cyccle", cycleValue.value);
      weekSelected.value = (cycleValue.value as string).split(",");
      console.log("cyccle", weekSelected.value);
    } else if (cyclePerUnit.value === "MONTH") {
      if (!cycleValue.value) {
        daySelected.value = [];
        return;
      }
      daySelected.value = (cycleValue.value as string).split(",");
    }
    if (cycleValue.value) {
      nextTick(() => {
        formItem?.value?.clearValidate();
      });
    }
  },
  { immediate: true }
);
onMounted(() => {
  queryCheckGroupSelect();
});
// 获取巡检组下拉列表
const queryCheckGroupSelect = async () => {
  const tempCheckGroupList = await queryDictData({ typeCode: "ERC_CHECK_PLAN_STATUS" });
  checkGroupList.value = tempCheckGroupList || [];
};

const handlePerUnitChange = val => {
  if (val !== "DAY") {
    if ((cyclePerNum.value as number) > 12) {
      cyclePerNum.value = 12;
    }
  }
  cycleValue.value = "";
  daySelected.value = [];
  monthSelected.value = [];
  weekSelected.value = [];
  emits("handlePerUnitChange", checkGroupVal.value);
};
const handlePerNumChange = () => {
  emits("handlePerNumChange", checkGroupVal.value);
};
const weekChange = val => {
  console.log(val);
  if (weekSelected.value.length === 0) {
    cycleValue.value = "";
    return;
  }
  cycleValue.value = weekSelected.value.join(",");
};
const dayChange = val => {
  console.log(val);
  if (daySelected.value.length === 0) {
    cycleValue.value = "";
    return;
  }
  if (["QUARTER", "HALF_YEAR", "YEAR"].includes(cyclePerUnit.value)) {
    cycleValue.value = `${monthSelected.value.join(",")}-${daySelected.value.join(",")}`;
  } else {
    cycleValue.value = daySelected.value.join(",");
  }
};
const monthChange = val => {
  console.log(val);
  if (monthSelected.value.length === 0) {
    cycleValue.value = "";
    return;
  }
  if (["QUARTER", "HALF_YEAR", "YEAR"].includes(cyclePerUnit.value)) {
    cycleValue.value = `${monthSelected.value.join(",")}-${daySelected.value.join(",")}`;
  } else {
    cycleValue.value = monthSelected.value.join(",");
  }
};
</script>
<style lang="scss" scoped>
.check-cycle-form {
  &-text {
    display: inline-block;
    margin-right: 15px;
    margin-left: 15px;
  }
}
</style>
